from skimage.transform import rotate
from skimage.feature import local_binary_pattern
from skimage import data
import numpy as np

# Settings for LBP
radius = 3
n_points = 8 * radius

# Get sample images to test the algorithm and convert them to integer type
brick = data.brick().astype(np.uint8)
grass = data.grass().astype(np.uint8)
wall = data.camera().astype(np.uint8)

# Calculate the LBP features for each image
brick_lbp = local_binary_pattern(brick, n_points, radius, 'uniform')
grass_lbp = local_binary_pattern(grass, n_points, radius, 'uniform')
wall_lbp = local_binary_pattern(wall, n_points, radius, 'uniform')

# Rotate images by 22 degrees and convert them to integer type
brick_rot = rotate(brick, angle=22, resize=False).astype(np.uint8)
grass_rot = rotate(grass, angle=22, resize=False).astype(np.uint8)
wall_rot = rotate(wall, angle=22, resize=False).astype(np.uint8)

# Calculate the LBP features for rotated images
brick_rot_lbp = local_binary_pattern(brick_rot, n_points, radius, 'uniform')
grass_rot_lbp = local_binary_pattern(grass_rot, n_points, radius, 'uniform')
wall_rot_lbp = local_binary_pattern(wall_rot, n_points, radius, 'uniform')

# Generate histogram for the original brick LBP image
bins_num = int(brick_lbp.max() + 1)
brick_hist, _ = np.histogram(brick_lbp, bins=bins_num, range=(0, bins_num), density=True)

# Compare the brick histogram with the rotated images
lbp_features = [brick_rot_lbp, grass_rot_lbp, wall_rot_lbp]
min_score = float('inf')
winner = -1

for idx, feature in enumerate(lbp_features):
    hist, _ = np.histogram(feature, bins=bins_num, range=(0, bins_num), density=True)
    p = np.asarray(brick_hist)
    q = np.asarray(hist)
    filter_idx = np.logical_and(p != 0, q != 0)
    score = np.sum(p[filter_idx] * np.log2(p[filter_idx] / q[filter_idx]))

    if score < min_score:
        min_score = score
        winner = idx

# Output the result
if winner == 0:
    print('Brick matched with Brick Rotated')
elif winner == 1:
    print('Brick matched with Grass Rotated')
elif winner == 2:
    print('Brick matched with Wall Rotated')
